package com.enbatis.mybatisplugs.base;

import com.enbatis.mybatisplugs.commons.utils.CodeMsg;
import com.enbatis.mybatisplugs.commons.utils.ResultReturn;
import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.SQLException;

@RestControllerAdvice
public class ControllerExceptionHandleAdvice {
    private final static Logger logger = LoggerFactory.getLogger(ControllerExceptionHandleAdvice.class);
    @ExceptionHandler
    public ResultReturn handler(HttpServletRequest req, HttpServletResponse res, Exception e) {
        logger.info("Restful Http请求发生异常...");

        if (res.getStatus() == HttpStatus.BAD_REQUEST.value()) {
            logger.info("修改返回状态值为200");
            res.setStatus(HttpStatus.OK.value());
        }

        if (e instanceof NullPointerException) {
            logger.error("代码00：" + e.getMessage(), e);
            return ResultReturn.error(CodeMsg.NULLPOINT);
        } else if (e instanceof IllegalArgumentException) {
            logger.error("代码01：" + e.getMessage(), e);
            return ResultReturn.error(CodeMsg.PARAM_NOT_OK);
        } else if (e instanceof SQLException) {
            logger.error("代码02：" + e.getMessage(), e);
            return ResultReturn.error(CodeMsg.SQL_EXCEPTION);
        } else if (e instanceof AuthorizationException) {
            logger.error("代码02：" + e.getMessage(), e);
            return ResultReturn.error(CodeMsg.AUTH_EXCEPTION);
        } else {
            logger.error("代码99：" + e.getMessage(), e);
            return ResultReturn.error(CodeMsg.SERVER_EXCEPTION);
        }
    }
}
